package awesome.site.loader;

import java.io.FileNotFoundException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.logging.Logger;

import awesome.site.loader.util.CheckSum;
import awesome.site.proprietor.SiteProprietor;
import awesome.site.proprietor.WebObjectProprietor;

/**
 * Removes deleted/old files from the SiteProprietor.
 * 
 * @author Chris Carpenter
 * 
 */
public class ProprietorUpdater {

	SiteProprietor proprietor;


	public ProprietorUpdater(SiteProprietor _proprietor) {
		this.proprietor = _proprietor;
	}

	/**
	 * Updates the site proprietor, deleting the outdated/removed files.
	 * 
	 */
	public void updateProprietor(){
		//iterate through all objects in proprietor
		Iterator<Entry<String, WebObjectProprietor>> proprietorIterator = proprietor.entrySet().iterator();
		WebObjectProprietor currProp;
		Path checkPath;
		while (proprietorIterator.hasNext()){
			currProp = proprietorIterator.next().getValue();
			checkPath = Paths.get(currProp.getWebFileName());
			if (!checkPath.toFile().exists()){ //if the file no longer exists
				Logger.getLogger("awesome.server").info(
						"Removing file because it no longer exists: " + currProp.getWebFileName());
				proprietorIterator.remove();
			} else {
				try {
					if (!CheckSum.getCheckSum(checkPath).equals(currProp.getID())){ //if checksum no longer matches
						Logger.getLogger("awesome.server").info(
								"Removing file because it is out of date: " + currProp.getWebFileName());
						proprietorIterator.remove(); //ok to simply remove, because FSL runs immediately afterward
					}
				} catch (NoSuchAlgorithmException | FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
